package com.baizhi.controller;

import com.baizhi.entity.User;
import com.baizhi.service.UserService;
import com.baizhi.utils.ValidateImageCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

@Controller
@RequestMapping("/user")  //???
public class UserController {

    @Autowired
    private UserService userService;


    //1.生成验证码
    @GetMapping("/getImage")
    public void getImage(HttpSession session, HttpServletResponse response) throws IOException {
        //生成验证码
        String securityCode = ValidateImageCodeUtils.getSecurityCode();
        //将验证码放入session
        session.setAttribute("code",securityCode);
        //生成图片
        BufferedImage image = ValidateImageCodeUtils.createImage(securityCode);
        //调用工具类
        ServletOutputStream os = response.getOutputStream();  //拿到输出流
        ImageIO.write(image,"png",os);
    }


    //2.开发用户注册
    @RequestMapping("/regist")
    public String regist(User user, String code, HttpSession session){

//        System.out.println("user===>" + user);

        //判断验证码是否通过
        if (session.getAttribute("code").toString().equalsIgnoreCase(code)){  //通过了才注册奥！
            userService.save(user);
            return "redirect:/ems/login.jsp";   //通过了跳到登录页面
        }else {
            return "redirect:/ems/regist.jsp";  //不通过回到注册页面
        }
    }


    //3.开发登录功能
    @RequestMapping("/login")
    public String login(String username, String password, HttpServletRequest request ){

        User user = userService.login(username, password);

        //如果为空则账户或密码错误，如果不为空则账号密码正确进行登录。
        if (user!=null){
            request.setAttribute("user",user);
            return "redirect:/emp/findAll";   //
            // 查询所有员工
//          return "redirect:/ems/emplist.jsp";
        }else{
            return "redirect:/ems/login.jsp";
        }
    }



}






























